import React, {useEffect, useState} from 'react';
import {format, formatDistanceToNow} from "date-fns";
import {ChartBarIcon, ChatIcon, DotsHorizontalIcon, HeartIcon, ShareIcon, TrashIcon} from
        "@heroicons/react/outline";
import {HeartIcon as HeartIconSolid} from "@heroicons/react/solid";
import {BACKEND_BATH_URL} from "@/lib/constants";
import {useRouter} from "next/navigation";
import {useOpenStore} from "@/hooks/forum/use-open-store";
import {usePostIdStore} from "@/hooks/forum/use-post-store";
import {useCurrentUser} from "@/hooks/use-current-user";
import {Avatar, AvatarFallback, AvatarImage} from "@/components/ui/avatar";
import zhCN from "date-fns/locale/zh-CN";
import {formatDateToNow} from "@/lib/format";

// todo: 如何实现多层comment
const Comment = ({comment, post}) => {
    const user = useCurrentUser()
    if (!user) return <div>loading...</div>
    const userId = user.id

    if (!post && !comment) return <div>loading...</div>
    const likeComment = async (e) => {
        if (hasLiked) {
            const id = likes.filter(l => l.commentId === comment.id)
            // await fetch(`${BACKEND_BATH_URL}/likes/${id[0].id}`, {
            await fetch(`/api/likes/${id[0].id}`, {
                method: 'Delete'
            })
        } else {
            await fetch(`/api/likes`, {
                method: 'POST',
                body: JSON.stringify({
                    commentId: comment.id,
                    username: user?.name,
                    userId
                }),
                headers: {
                    "Content-Type": "application/json",
                }
            })
        }
    }

    const [likes, setLikes] = useState([])
    const [hasLiked, setHasLiked] = useState(false)
    useEffect(() => {
        (async () => {
            // const likeFetch = await fetch(`${BACKEND_BATH_URL}/likes?commentId=${comment.id}`)
            const likeFetch = await fetch(`/api/likes/comment/${comment.id}`)
            const ls = await likeFetch.json()
            // setLikes(ls.filter(l => l.postId === post.id))
            setLikes(ls.likes)
        })()
    }, [])
    useEffect(() => {
        if (!likes) return
        setHasLiked((likes?.findIndex(l => l.userId === userId) !== -1))
    }, [likes])

    const router = useRouter()
    const deleteComment = () => {
        // delete img
        // delete likes
        // delete comments

        // delete data
        // fetch(`${BACKEND_BATH_URL}/comments/${comment.id}`, {
        fetch(`/api/comments/${comment.id}`, {
            method: 'DELETE',
        })

        router.push('/forum')
    }

    const {setOpen, open} = useOpenStore()
    const {postId, setPostId} = usePostIdStore()


    return (
        <div className={`flex p-3 cursor-pointer border-b border-gray-200 pl-20`}>
            {/*image*/}{/*当前评论用户头像*/}
            <Avatar className={`size-11 mr-2 rounded-full`}>
                <AvatarImage className={`rounded-full`} src={post.userImg}/>
                <AvatarFallback className={`bg-blue-400 text-white rounded-full`}>
                    {post.username && post.username.charAt(0).toUpperCase()}
                </AvatarFallback>
            </Avatar>
            {/*<img*/}
            {/*    className={`size-11 rounded-full mr-4`}*/}
            {/*    src={post.userImg} alt="user img"/>*/}
            <div className={`flex-1 flex-grow`}>
                {/*header*/}
                <div className={`flex items-center justify-between `}>
                    {/*post user info*/}
                    <div className={`flex items-center space-x-1 whitespace-nowrap`}>
                        {/*昵称*/}
                        <h4 className={`font-bold text-[15px] sm:text-[16px] 
                        hover:underline`}>{comment.name}</h4>
                        {/*账号name*/}
                        <span className={`text-sm sm:text-[15px]`}
                        >@{comment.username} - </span>
                        <span className={`text-sm sm:text-[15px] hover:underline`}
                        >
                            {/*{comment.timestamp && format(parseInt(comment?.timestamp), 'yyyy-MM-dd')}*/}
                            {comment.timestamp && `${formatDateToNow((comment?.timestamp))}前`}
                            {/*{post?.timestamp}*/}
                        </span>
                    </div>
                    {/*dot icon*/}
                    <DotsHorizontalIcon className={`size-10 hoverEffect hover:bg-sky-100 hover:text-sky-500 p-2`}/>
                </div>
                {/*post text*/}
                <p className={`text-gray-800 text-[15px] sm:text[16px] mb-2`}>{comment.comment}</p>
                {/*post image*/}
                <img className={`rounded-2xl mr-2`}
                     src={comment.img} alt=""/>
                {/*icons*/}
                <div className={`flex justify-between text-gray-500 p-2`}>
                    <div className={`flex items-center select-none`}>
                        <ChatIcon
                            onClick={() => {
                                // if(!logined ){}else
                                setPostId(post?.id)
                                setOpen(!open)
                                console.log(open)
                            }}
                            className={'size-9 hoverEffect p-2 hover:text-sky-500 hover:bg-sky-100'}/>
                    </div>
                    {userId === post.userId && (
                        <TrashIcon
                            onClick={deleteComment}
                            className={'size-9 hoverEffect p-2 hover:text-red-600 hover:bg-red-100'}/>
                    )}
                    <div className={`flex items-center`}>
                        {!hasLiked && <HeartIcon
                            onClick={likeComment}
                            className={'size-9 hoverEffect p-2 hover:text-red-600 hover:bg-red-100'}/>}
                        {hasLiked && <HeartIconSolid
                            onClick={likeComment}
                            className={'size-9 hoverEffect p-2 text-red-600 hover:bg-red-100'}/>}
                        {likes && <span className={`pt-0.5`}>{likes.length}</span>}
                    </div>
                    <ShareIcon className={'size-9 hoverEffect p-2 hover:text-sky-500 hover:bg-sky-100'}/>
                    <ChartBarIcon className={'size-9 hoverEffect p-2 hover:text-sky-500 hover:bg-sky-100'}/>
                </div>
            </div>
        </div>
    );
};

export default Comment;